package com.xctech.ipb.dpn.hyc.listener;

import com.xctech.ipb.dpn.common.utils.JsonUtils;
import com.xctech.ipb.dpn.framework.cache.service.FileCacheService;
import com.xctech.ipb.dpn.hyc.constant.TopicConstants;
import com.xctech.ipb.dpn.hyc.domain.service.StationService;
import com.xctech.ipb.dpn.hyc.model.dto.FileCacheMessage;
import com.xctech.ipb.dpn.hyc.model.req.DeviceInfoReq;
import com.xctech.ipb.dpn.hyc.model.req.StationInfoReq;
import com.xctech.ipb.dpn.hyc.model.req.StationReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class StationListener {

    private static final Logger log = LoggerFactory.getLogger(StationListener.class);

    @Autowired
    private StationService stationService;

    @Autowired
    private FileCacheService fileCacheService;

    @KafkaListener(topics = TopicConstants.TOPIC_STATION_SYNC, groupId = "rwa-dpn-group")
    public void listen(String message) {

        try {
            log.info("同步站点信息-开始");
            //还原body体
            StationReq req = JsonUtils.fromJson(message, StationReq.class);
            log.info("同步站点信息-消息体: {}", req);
            int row = stationService.syncStation(req.getStationInfoList());
            log.info("同步站点信息结束-成功: {}", row);

        } catch (Exception e) {

            log.error("同步站点信息结束-失败: {}", e.getMessage());

        }


    }

    @KafkaListener(topics = TopicConstants.TOPIC_STATION_SYNC_ALL, groupId = "rwa-dpn-group")
    public void listenSyncAll(String message) {

        try {
            log.info("同步全量站点信息-开始");
            FileCacheMessage fileCacheMessage = JsonUtils.fromJson(message, FileCacheMessage.class);
            log.info("同步全量站点信息-文件:{}", fileCacheMessage);
            List<StationInfoReq> list = fileCacheService.readData(fileCacheMessage.getFileName(), StationInfoReq.class);
            log.info("同步全量站点信息-读取成功:{}", list.size());
            int row = stationService.syncStation(list);
            log.info("同步全量站点信息结束-成功: {}", row);
            fileCacheService.deleteFile(fileCacheMessage.getFileName());
        } catch (Exception e) {
            log.error("同步全量站点信息结束-失败: {}", e.getMessage());
        }
    }

}
